package com.ruicar.afs.cloud.apply.pre.loan.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.common.entity.*;
import com.ruicar.afs.cloud.apply.common.feign.Apply2ChannelFeign;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConfig;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.contract.service.ApplyBankCardService;
import com.ruicar.afs.cloud.apply.contract.service.ApplyCarInvoiceService;
import com.ruicar.afs.cloud.apply.contract.service.ApplyContractInfoService;
import com.ruicar.afs.cloud.apply.pre.loan.condition.CaseSubmitInfoCondition;
import com.ruicar.afs.cloud.apply.pre.loan.service.*;
import com.ruicar.afs.cloud.apply.pre.loan.vo.FilterParamsVO;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinFinancingItems;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyCostDetailsService;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyFinancingItemsService;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum;
import com.ruicar.afs.cloud.parameter.commom.enums.OperateWay;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

/**
 * 影像件 Controller
 *
 * @author 耿继辉
 */
@RestController
@AllArgsConstructor
@RequestMapping("/applyFilter")
@Slf4j
public class FilterParamsController {
    private final ApplyOrderInfoService applyOrderInfoService;
    private final ApplyCarDetailsService applyCarDetailsService;
    private final ApplyChannelInfoService applyChannelInfoService;
    private final ApplyFinancingItemsService applyFinancingItemsService;
    private final ApplyCostDetailsService applyCostDetailsService;
    private final ApplyCustBaseInfoService applyCustBaseInfoService;
    private final ApplyBankCardService applyBankCardService;
    private final ApplyContractInfoService applyContractInfoService;
    private final ApplyCustPersonalService applyCustPersonalService;
    private final ApplyCarInvoiceService applyCarInvoiceService;
    private ApplyConfig config;
    private Apply2ChannelFeign apply2ChannelFeign;
    /**
     * 影像件需要数据拼装
     *
     * @param condition
     * @return
     */
    @PostMapping("/getFilterParams")
    public IResponse getFilterParams(@RequestBody CaseSubmitInfoCondition condition) {
        FilterParamsVO filterParamsVO = new FilterParamsVO();
        String applyNo = condition.getApplyNo();
        if (StringUtil.isEmpty(applyNo)) {
            return IResponse.success(null);
        }
        //订单主表
        ApplyOrderInfo orderInfoByApplyNo = this.applyOrderInfoService.getOrderInfoByApplyNo(applyNo);
        //车辆信息主表
        ApplyCarDetails carDetailsByApplyNo = this.applyCarDetailsService.getCarDetailsByApplyNo(applyNo);
        //渠道信息表
        ApplyChannelInfo channelInfoByApplyNo = this.applyChannelInfoService.getChannelInfoByApplyNo(applyNo);
        //融资项信息
        List<FinFinancingItems> applyFinancingItemsList = this.applyFinancingItemsService.getApplyFinancingItemsList(applyNo);
        //融资信息
        List<FinCostDetails> costDetailsList = this.applyCostDetailsService.getCostDetailsList(applyNo);
        //主借人
        ApplyCustBaseInfo maBaseInfo = this.applyCustBaseInfoService.getCustBaseInfo(applyNo, ApplyConstants.PRINCIPAL_BORROWER);
        //共借人
        ApplyCustBaseInfo comBaseInfo = this.applyCustBaseInfoService.getCustBaseInfo(applyNo, ApplyConstants.COMMON_BORROWER);
        //担保人
        ApplyCustBaseInfo guarnBaseInfo = this.applyCustBaseInfoService.getCustBaseInfo(applyNo, ApplyConstants.GUARANTOR);
        //银行信息
        ApplyBankCard cardServiceOne = this.applyBankCardService.getOne(Wrappers.<ApplyBankCard>query().lambda()
                .eq(StringUtil.isNotEmpty(applyNo), ApplyBankCard::getApplyNo, applyNo));
        //合同信息
        ApplyContractInfo contractInfoServiceOne = this.applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda()
                .eq(StringUtil.isNotEmpty(applyNo), ApplyContractInfo::getApplyNo, applyNo));
        //个人明细信息
        ApplyCustPersonalDetail personalDetailForMain = this.applyCustPersonalService.getPersonalDetailForMain(condition.getApplyNo(), ApplyConstants.PRINCIPAL_BORROWER);
        //发票信息
        ApplyCarInvoice applyCarInvoice=this.applyCarInvoiceService.getApplyCarInvoice(condition.getApplyNo());
        if(applyCarInvoice!=null){
            filterParamsVO.setMakeInvoiceUnit(applyCarInvoice.getInvoiceUnit()==null?"":applyCarInvoice.getInvoiceUnit());
        }
        filterParamsVO.setChannelId(SecurityUtils.getUser().getUserExtInfo().getLong("channelId").toString());
        if (ObjectUtil.isNotNull(orderInfoByApplyNo)) {
            //业务类型
            filterParamsVO.setBusinessType(orderInfoByApplyNo.getBusinessType());
            //挂靠方式
            filterParamsVO.setAffiliatedWay(orderInfoByApplyNo.getAffiliatedWay());
            //车辆属性
            filterParamsVO.setCarNature(orderInfoByApplyNo.getCarNature());
            //运营方式
            filterParamsVO.setOperateWay(orderInfoByApplyNo.getOperateWay());
            //是否网约车
            if (OperateWay.NETWORK_CAR.getIndex().equals(orderInfoByApplyNo.getOperateWay())) {
                filterParamsVO.setOnlineCar(com.ruicar.afs.cloud.parameter.commom.enums.WhetherEnum.YES.getIndex());
            } else {
                filterParamsVO.setOnlineCar(com.ruicar.afs.cloud.parameter.commom.enums.WhetherEnum.No.getIndex());
            }
            //车辆类型
            filterParamsVO.setCarType(orderInfoByApplyNo.getCarType());
        }
        if (ObjectUtil.isNotNull(channelInfoByApplyNo)) {
            //合作商名称
            filterParamsVO.setDealerName(channelInfoByApplyNo.getChannelName());
            //合作商优质等级
            filterParamsVO.setQualityGrade(channelInfoByApplyNo.getQualityGrade());
            //渠道归属
            filterParamsVO.setChannelBelong(channelInfoByApplyNo.getChannelBelong());
        }
        if (ObjectUtil.isNotNull(carDetailsByApplyNo)) {
            //车辆级别
            filterParamsVO.setCarBodyClass(carDetailsByApplyNo.getCarBodyClass());
            //是否新能源
            filterParamsVO.setIsGreen(carDetailsByApplyNo.getIsGreen());
        }
        if (CollectionUtil.isNotEmpty(applyFinancingItemsList)) {
            BigDecimal c = new BigDecimal("0.00");
            for (FinFinancingItems finFinancingItems : applyFinancingItemsList) {
                if (finFinancingItems.getFinanceItemAmt() != null) {
                    c = c.add(finFinancingItems.getFinanceItemAmt());
                }
            }
            //附加贷金额
            filterParamsVO.setAppendAmount(c);
        }

        BigDecimal hundred = new BigDecimal("100");
        if (CollectionUtil.isNotEmpty(costDetailsList)) {
            BigDecimal carLoanAmount = BigDecimal.ZERO;
            BigDecimal loanAmount = BigDecimal.ZERO;
            for (FinCostDetails finCostDetails : costDetailsList) {
                //金融产品
                if (ApplyConstants.COST_TYPE_CAR_LOAN.equals(finCostDetails.getCostType())) {
                    filterParamsVO.setProductId(finCostDetails.getProductId());
                    BigDecimal downPayScale = finCostDetails.getDownPayScale();
                    //车贷金额
                    carLoanAmount = finCostDetails.getContractAmt().multiply(hundred.subtract(downPayScale)).divide(hundred,2,BigDecimal.ROUND_HALF_DOWN);
                    //还款方式
                    filterParamsVO.setRepayMode(finCostDetails.getAlgorithmType());
                    loanAmount = loanAmount.add(finCostDetails.getLoanAmt());
                    if("0".equals(finCostDetails.getIsSubProduct())){
                        loanAmount = loanAmount.add(finCostDetails.getAddAmt());
                    }
                }else if(ApplyConstants.COST_TYPE_ADD_LOAN.equals(finCostDetails.getCostType())){
                    loanAmount = loanAmount.add(finCostDetails.getLoanAmt());
                }
            }
            filterParamsVO.setCarLoanAmount(carLoanAmount);
            filterParamsVO.setLoanAmount(loanAmount);
        }
        if (ObjectUtil.isNotNull(comBaseInfo)) {
            //有共借人
            filterParamsVO.setHasCommonBorrower(WhetherEnum.YES.getCode());
        } else {
            //无共借人
            filterParamsVO.setHasCommonBorrower(WhetherEnum.NO.getCode());
        }
        if (ObjectUtil.isNotNull(guarnBaseInfo)) {
            //有担保人
            filterParamsVO.setHasBail(WhetherEnum.YES.getCode());
        } else {
            //无担保人
            filterParamsVO.setHasBail(WhetherEnum.NO.getCode());
        }
        if (ObjectUtil.isNotNull(cardServiceOne)) {
            //还款卡银行
            filterParamsVO.setBankCode(cardServiceOne.getBankCode());
            //是否电子授权
            if ("offline".equals(cardServiceOne.getAuthorizeWay())) {
                filterParamsVO.setLendingMode(WhetherEnum.NO.getCode());
            } else if ("online".equals(cardServiceOne.getAuthorizeWay())) {
                filterParamsVO.setLendingMode(WhetherEnum.YES.getCode());
            }
        }
        //放款模式
        if (ObjectUtil.isNotNull(contractInfoServiceOne)) {
            filterParamsVO.setLendingMode(contractInfoServiceOne.getLendingMode());
            filterParamsVO.setContractNo(contractInfoServiceOne.getContractNo());
        }
        if (ObjectUtil.isNotNull(personalDetailForMain)) {
            //是否存在档案编号
            if (StringUtil.isNotEmpty(personalDetailForMain.getDrivingLicenceNo())) {
                filterParamsVO.setHasLicenseNum(WhetherEnum.YES.getCode());
            } else {
                filterParamsVO.setHasLicenseNum(WhetherEnum.NO.getCode());
            }
            //驾驶证件
            if (StringUtil.isNotEmpty(personalDetailForMain.getDrivingType())) {
                filterParamsVO.setDrivingType(personalDetailForMain.getDrivingType());
            }
        }
        log.info("规则参数:{}", filterParamsVO);
        return IResponse.success(filterParamsVO);
    }
}
